package roomlogic

import (
	"OemServer/internal/svc"
	"OemServer/pb"
	"common/comCopier"
	"common/dao/model"
	comJwt "common/jwt"
	"common/utils"
	"context"
	"errors"
	"gorm.io/gorm"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
	return &CreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateLogic) Create(in *pb.RoomInfo) (*pb.Emp, error) {
	// todo: add your logic here and delete this line
	if in.RoomName == "" {
		return nil, errors.New("roomName is null")
	}
	if in.RoomPhoto == "" {
		return nil, errors.New("roomPhoto is null")
	}
	//if in.RoomAddress == "" {
	//	return nil, errors.New("RoomAddress is null")
	//}
	if in.RoomStatus != 1 && in.RoomStatus != 2 {
		return nil, errors.New("RoomStatus is type 1 or 2")
	}
	if in.RoomInformation == "" {
		return nil, errors.New("RoomInformation is null")
	}
	jwtUser, err := comJwt.BackUser(l.ctx, l.svcCtx.Config.USERDATA)
	if err != nil {
		return nil, err
	}
	var (
		roomData   = model.Room{}
		oldRoom    = model.Room{}
		roomConfig = model.RoomConfig{}
	)

	if err := comCopier.CopyWithOption(&roomData, in); err != nil {
		return nil, err
	}
	if err := comCopier.CopyWithOption(&roomConfig, in); err != nil {
		return nil, err
	}
	roomConfig.UserUUID = jwtUser.UUID
	roomData.UUID = utils.GetUuid()
	t := time.Now()
	roomData.CreateTime = &t
	roomData.Status = 1
	roomData.RoomUuids = roomData.UUID
	roomData.UserUUID = jwtUser.UUID
	db := l.svcCtx.DB

	err = db.Transaction(func(tx *gorm.DB) error {
		table1 := tx.Table(model.TableNameRoom)
		table2 := tx.Table(model.TableNameGroup)
		table3 := tx.Table(model.TableNameGroupMember)
		if err := tx.Where("user_uuid = ?", jwtUser.UUID).Where("is_del = 0").First(&oldRoom).Error; err != nil {
			//return err
		}
		if oldRoom.Status == 1 && oldRoom.UUID != "" {
			return errors.New("你已有的房间正在直播中")
		}
		var (
			group        model.Group
			groupMembers model.GroupMember
		)
		group.GroupName = in.RoomName
		group.CreateTime = &t
		if err := table2.Create(&group).Error; err != nil {
			return err
		}
		roomData.RoomMessagesGroupsID = group.ID
		if err := table1.Create(&roomData).Error; err != nil {
			return err
		}
		groupMembers.GroupID = group.ID
		groupMembers.UserUUID = jwtUser.UUID
		t := time.Now()
		groupMembers.JoinedAt = &t
		if err := table3.Create(&groupMembers).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &pb.Emp{}, nil
}
